jQuery(function(){
    var preloader = jQuery('#fetchPostsPreloader');
    var fetchPostsMessage = jQuery('#fetchPostsMessage');
    var fetchSuccessMessageContainer = jQuery('#fetchSuccessMessage');
    var fetchProcessContainer = jQuery('#fetchProcessContainer');
    fetchProcessContainer.hide();
    var ajaxRequest = null;

    jQuery('#grabForm').submit(function(event){
        event.preventDefault();
        fetchProcessContainer.show();
        fetchSuccessMessageContainer.empty();
        ajaxRequest = jQuery.ajax({
            type: 'POST',
            url: jQuery(this).attr('action'),
            success: function(response) {
                var messageText = (response == "1") ? "Posts have been fetched" : "There was an error during posts fetch.";
                fetchSuccessMessageContainer.text(messageText);
                fetchProcessContainer.hide();
            }
        });
        return false;
    });

    jQuery('#stopFetchButton').click(function(event){
        if (ajaxRequest != null)
        {
            ajaxRequest.abort();
            fetchProcessContainer.hide();
        }
    });

    jQuery('#addSourceForm').submit(function(event){
        event.preventDefault();
        jQuery.ajax({
            type: 'POST',
            url: jQuery(this).attr('action'),
            data: jQuery(this).serialize(),
            success: function(response) {
                location.reload();
            }
        });
        return false;
    });

    jQuery('.delete_source').click(function(event){
        event.preventDefault();
        jQuery.ajax({
            type: 'GET',
            url: jQuery(this).attr('href'),
            success: function(response) {
                location.reload();
            }
        });
    });

    jQuery('.source_url').blur(function(event){
        var newUrl = jQuery(this).text();
        jQuery.ajax({
            type: 'POST',
            url: jQuery('#optionsUrl').val(),
            data: {
                id: jQuery(this).next('.rss_info_id').val(),
                action: 'update',
                new_url: newUrl
            },
            success: function(response) {
                location.reload();
            }
        });

    });
});